package com.unimod.fsml.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;

/**
 * Utility class that works with Eclipse core objects.
 *
 * @author Ivan Lagunov
 */
public class CoreUtils {

	/**
	 * Creates a signature string for given unresolved class.
	 * 
	 * @param clazz the class to create signature for.
	 * @return a signature string for given unresolved class.
	 */
	@SuppressWarnings("unchecked")
	public static String createClassSignature(Class clazz) {
		return Signature.createTypeSignature(clazz.getSimpleName(), false);
	}

	/**
	 * Loads interfaces implemented in given compilation unit.
	 * 
	 * @param element compilation unit to load interfaces from.
	 * @return the set of signatures for loaded interfaces. 
	 * @throws JavaModelException if loading interfaces failed.
	 */
	public static Set<String> getInterfaces(ICompilationUnit element) throws JavaModelException {
		return getInterfaces(element.findPrimaryType());
	}
	
	private static Set<String> getInterfaces(IType type) throws JavaModelException {
		Set<String> interfaces = new HashSet<String>();
		interfaces.addAll(Arrays.asList(type.getSuperInterfaceTypeSignatures()));
		
		for (IType superType : type.newSupertypeHierarchy(null).getSupertypes(type)) {
			interfaces.addAll(getInterfaces(superType));
		}
		
		return interfaces;
	} 
}
